package handlers

import (
	"context"
	"ourplansystem/server/ent"
	"ourplansystem/server/models"
	"strconv"
	"time"

	"github.com/gofiber/fiber/v2"
)

// DailyCheckinHandler 每日打卡处理器
type DailyCheckinHandler struct {
	client *ent.Client
}

// NewDailyCheckinHandler 创建每日打卡处理器
func NewDailyCheckinHandler(client *ent.Client) *DailyCheckinHandler {
	return &DailyCheckinHandler{client: client}
}

// CreateDailyCheckinRequest 创建打卡请求
type CreateDailyCheckinRequest struct {
	UserID      int64  `json:"user_id"`
	Type        string `json:"type"` // 早安/晚安
	Mood        string `json:"mood"`
	Note        string `json:"note"`
	CheckinDate string `json:"checkin_date"` // 格式: 2006-01-02
}

// GetDailyCheckins 获取所有打卡记录
func (h *DailyCheckinHandler) GetDailyCheckins(c *fiber.Ctx) error {
	ctx := context.Background()
	checkins, err := h.client.DailyCheckin.Query().WithUser().All(ctx)
	if err != nil {
		return models.InternalServerError(c, "获取打卡记录失败")
	}

	return models.Success(c, checkins)
}

// GetDailyCheckin 获取单个打卡记录
func (h *DailyCheckinHandler) GetDailyCheckin(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的打卡ID")
	}

	checkin, err := h.client.DailyCheckin.Get(ctx, id)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "打卡记录不存在")
		}
		return models.InternalServerError(c, "获取打卡记录失败")
	}

	return models.Success(c, checkin)
}

// GetUserCheckins 获取指定用户的打卡记录
func (h *DailyCheckinHandler) GetUserCheckins(c *fiber.Ctx) error {
	ctx := context.Background()
	userID, err := strconv.ParseInt(c.Params("userId"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的用户ID")
	}

	checkins, err := h.client.DailyCheckin.Query().
		Where().
		WithUser().
		All(ctx)
	if err != nil {
		return models.InternalServerError(c, "获取打卡记录失败")
	}

	// 过滤出该用户的打卡记录
	var userCheckins []*ent.DailyCheckin
	for _, checkin := range checkins {
		if checkin.UserID == userID {
			userCheckins = append(userCheckins, checkin)
		}
	}

	return models.Success(c, userCheckins)
}

// CreateDailyCheckin 创建打卡记录
func (h *DailyCheckinHandler) CreateDailyCheckin(c *fiber.Ctx) error {
	ctx := context.Background()
	var req CreateDailyCheckinRequest
	if err := c.BodyParser(&req); err != nil {
		return models.BadRequest(c, "请求参数错误")
	}

	if req.UserID == 0 {
		return models.BadRequest(c, "用户ID不能为空")
	}

	if req.Type == "" {
		return models.BadRequest(c, "打卡类型不能为空")
	}

	builder := h.client.DailyCheckin.
		Create().
		SetUserID(req.UserID).
		SetType(req.Type)

	if req.Mood != "" {
		builder.SetMood(req.Mood)
	}

	if req.Note != "" {
		builder.SetNote(req.Note)
	}

	if req.CheckinDate != "" {
		checkinDate, err := time.Parse("2006-01-02", req.CheckinDate)
		if err != nil {
			return models.BadRequest(c, "打卡日期格式错误，应为: 2006-01-02")
		}
		builder.SetCheckinDate(checkinDate)
	}

	checkin, err := builder.Save(ctx)
	if err != nil {
		return models.InternalServerError(c, "创建打卡记录失败")
	}

	return models.SuccessWithMessage(c, "打卡成功", checkin)
}

// DeleteDailyCheckin 删除打卡记录
func (h *DailyCheckinHandler) DeleteDailyCheckin(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的打卡ID")
	}

	err = h.client.DailyCheckin.DeleteOneID(id).Exec(ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "打卡记录不存在")
		}
		return models.InternalServerError(c, "删除打卡记录失败")
	}

	return models.SuccessWithMessage(c, "删除成功", nil)
}
